package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Result;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import com.itheima.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/clazzs")
@RestController
public class ClazzController {
    @Autowired
    private ClazzService clazzService;
    @Autowired
    private EmpService empService;

    @GetMapping
    public Result list(String name,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end,
                       @RequestParam(defaultValue = "1") int page,
                       @RequestParam(defaultValue = "10") int pageSize) {
        log.info("查询班级列表");
        Page<Clazz> pageClazz = new Page<>(page, pageSize);
        LambdaQueryWrapper<Clazz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(begin != null, Clazz::getBeginDate, begin)
                .le(end != null, Clazz::getEndDate, end)
                .like(name != null && name.length() > 0, Clazz::getName, name)
        ;
        pageClazz.addOrder(OrderItem.desc("update_time"));
        pageClazz = clazzService.page(pageClazz, queryWrapper);
        List<Clazz> clazzs = pageClazz.getRecords();
        if (clazzs != null && clazzs.size() > 0) {

            Set<Integer> empIds = clazzs.stream().filter(clazz -> clazz.getMasterId() != null)
                    .map(Clazz::getMasterId).collect(Collectors.toSet());
            log.info("empIds{}", empIds);
            Map<Integer, String> collect = empService.list(new LambdaQueryWrapper<Emp>().in(Emp::getId, empIds))
                    .stream().collect(Collectors.toMap(Emp::getId, Emp::getName));
            for (Clazz clazz : clazzs) {
                clazz.setMasterName(collect.get(clazz.getMasterId()));
                LocalDate now = LocalDate.now();
                String s = now.isAfter(clazz.getEndDate()) ? "已结束" : (now.isAfter(clazz.getBeginDate()) ? "进行中" : "未开始");
                clazz.setStatus(s);
            }
        }

        return Result.success(new PageResult<>(pageClazz.getTotal(), clazzs));
    }

    @PostMapping
    public Result save(@RequestBody Clazz clazz) {
        log.info("新增班级：{}", clazz);
        boolean r = clazzService.saveClass(clazz);
        return r ? Result.success() : Result.error("新增失败");
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据id查询班级：{}", id);
        Clazz clazz = clazzService.getById(id);

        if (clazz.getMasterId() != null) {
            Emp emp= empService.getById(clazz.getMasterId());

            clazz.setMasterName(emp==null?"已离职": emp.getName());
            LocalDate now = LocalDate.now();
            String s = now.isAfter(clazz.getEndDate()) ? "已结束" : (now.isAfter(clazz.getBeginDate()) ? "进行中" : "未开始");
            clazz.setStatus(s);
        }
        return Result.success(clazz);
    }

    @PutMapping
    public Result update(@RequestBody Clazz clazz) {
        log.info("修改班级：{}", clazz);
        boolean r = clazzService.updateClass(clazz);
        return r ? Result.success() : Result.error("修改失败");
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        log.info("删除班级：{}", id);
        boolean r = clazzService.removeById(id);
        return r ? Result.success() : Result.error("删除失败");
    }

    @GetMapping("/list")
    public Result list() {
        log.info("查询全部班级");
         List<Clazz> clazzs = clazzService.list();
        return Result.success(clazzs);
    }
}
